import api from '@/utils/request2'

const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']

// Define the description and icon of the weather
const weathers = {
    CLEAR_DAY: { description: '晴（白天）', icon: '#icon-qing' },
    CLEAR_NIGHT: { description: '晴（夜间）', icon: '#icon-qing' },
    PARTLY_CLOUDY_DAY: { description: '多云（白天）', icon: '#icon-yun' },
    PARTLY_CLOUDY_NIGHT: { description: '多云（夜间）', icon: '#icon-yun' },
    CLOUDY: { description: '阴', icon: '#icon-yin' },
    LIGHT_HAZE: { description: '轻度雾霾', icon: '#icon-unknown' },
    MODERATE_HAZE: { description: '中度雾霾', icon: '#icon-unknown' },
    HEAVY_HAZE: { description: '重度雾霾', icon: '#icon-unknown' },
    LIGHT_RAIN: { description: '小雨', icon: '#icon-yu' },
    MODERATE_RAIN: { description: '中雨', icon: '#icon-yu' },
    HEAVY_RAIN: { description: '大雨', icon: '#icon-yu' },
    STORM_RAIN: { description: '暴雨', icon: '#icon-yu' },
    FOG: { description: '雾', icon: '#icon-unknown' },
    LIGHT_SNOW: { description: '小雪', icon: '#icon-unknown' },
    MODERATE_SNOW: { description: '中雪', icon: '#icon-unknown' },
    HEAVY_SNOW: { description: '大雪', icon: '#icon-unknown' },
    STORM_SNOW: { description: '暴雪', icon: '#icon-unknown' },
    DUST: { description: '浮尘', icon: '#icon-unknown' },
    SAND: { description: '沙尘', icon: '#icon-unknown' },
    WIND: { description: '大风', icon: '#icon-unknown' }
}

// Define the wind force levels and their corresponding wind speed ranges
const windForceLevels = [
    { level: 0, speedRange: { min: 0, max: 1 }, description: '无风' },
    { level: 1, speedRange: { min: 1, max: 5 }, description: '微风徐徐' },
    { level: 2, speedRange: { min: 6, max: 11 }, description: '清风' },
    { level: 3, speedRange: { min: 12, max: 19 }, description: '树叶摇摆' },
    { level: 4, speedRange: { min: 20, max: 28 }, description: '树枝摇动' },
    { level: 5, speedRange: { min: 29, max: 38 }, description: '风力强劲' },
    { level: 6, speedRange: { min: 39, max: 49 }, description: '风力强劲' },
    { level: 7, speedRange: { min: 50, max: 61 }, description: '风力超强' },
    { level: 8, speedRange: { min: 62, max: 74 }, description: '狂风大作' },
    { level: 9, speedRange: { min: 75, max: 88 }, description: '狂风呼啸' },
    { level: 10, speedRange: { min: 89, max: 102 }, description: '暴风毁树' },
    { level: 11, speedRange: { min: 103, max: 117 }, description: '暴风毁树' },
    { level: 12, speedRange: { min: 118, max: 133 }, description: '飓风' },
    { level: 13, speedRange: { min: 134, max: 149 }, description: '台风' },
    { level: 14, speedRange: { min: 150, max: 166 }, description: '强台风' },
    { level: 15, speedRange: { min: 167, max: 183 }, description: '强台风' },
    { level: 16, speedRange: { min: 184, max: 201 }, description: '超强台风' },
    { level: 17, speedRange: { min: 202, max: 220 }, description: '超强台风' }
]

const windDirections = [
    { direction: '北', symbol: 'N', centerAngle: 0, range: [348.76, 11.25] },
    { direction: '北东北', symbol: 'NNE', centerAngle: 22.5, range: [11.26, 33.75] },
    { direction: '东北', symbol: 'NE', centerAngle: 45, range: [33.76, 56.25] },
    { direction: '东东北', symbol: 'ENE', centerAngle: 67.5, range: [56.26, 78.75] },
    { direction: '东', symbol: 'E', centerAngle: 90, range: [78.76, 101.25] },
    { direction: '东东南', symbol: 'ESE', centerAngle: 112.5, range: [101.26, 123.75] },
    { direction: '东南', symbol: 'SE', centerAngle: 135, range: [123.76, 146.25] },
    { direction: '南东南', symbol: 'SSE', centerAngle: 157.5, range: [146.26, 168.75] },
    { direction: '南', symbol: 'S', centerAngle: 180, range: [168.76, 191.25] },
    { direction: '南西南', symbol: 'SSW', centerAngle: 202.5, range: [191.26, 213.75] },
    { direction: '西南', symbol: 'SW', centerAngle: 225, range: [213.76, 236.25] },
    { direction: '西西南', symbol: 'WSW', centerAngle: 247.5, range: [236.26, 258.75] },
    { direction: '西', symbol: 'W', centerAngle: 270, range: [258.76, 281.25] },
    { direction: '西西北', symbol: 'WNW', centerAngle: 292.5, range: [281.26, 303.75] },
    { direction: '西北', symbol: 'NW', centerAngle: 315, range: [303.76, 326.25] },
    { direction: '北西北', symbol: 'NNW', centerAngle: 337.5, range: [326.26, 348.75] }
]

const getWindForceLevel = windSpeed => {
    // Find the wind force level using the wind speed
    const windForce = windForceLevels.find(
        level => windSpeed >= level.speedRange.min && windSpeed <= level.speedRange.max
    )

    // Return the wind force level and the corresponding description
    return {
        level: windForce ? windForce.level : 0,
        description: windForce ? windForce.description : '风速超出范围'
    }
}

const // Fetch daily weather data based on latitude, longitude, and number of days
    getDailyWeather = (latitude, longitude, days) => {
        const path = `/dailyWeather?latitude=${latitude}&longitude=${longitude}&days=${days}`
        return api.get(path)
    }

const // Fetch hourly weather data based on latitude, longitude, and number of hours
    getHourlyWeather = (latitude, longitude, hours) => {
        const path = `/hourlyWeather?latitude=${latitude}&longitude=${longitude}&hours=${hours}`
        return api.get(path)
    }

const // Fetch minutely weather data based on latitude, longitude, and number of minutes
    getMinutelyWeather = (latitude, longitude, minutes) => {
        const path = `/minutelyWeather?latitude=${latitude}&longitude=${longitude}&minutes=${minutes}`
        return api.get(path)
    }

const get7DaysWeatherData = async (latitude = 113.08220064926728, longitude = 22.708824208660197, days = 7) => {
    try {
        const response = await // Fetch daily weather data based on latitude, longitude, and number of days
        getDailyWeather(latitude, longitude, days)
        console.log(response);
        const data = JSON.parse(response.data)
       
        if (data.status !== 200 && data.status !== 'ok') {
            console.error(`API returned error with status code: ${data.status}`)
        } else {
            return processWeatherData(data, days)
        }
    } catch (error) {
        throw new Error('接口请求失败：' + error)
    }
    throw new Error('接口请求失败')
}

const // Process the fetched weather data for a specific number of days
    processWeatherData = (data, days) => {
        const result = []
        for (let i = 0; i < days; i++) {
            const dateDetails = getDateDetails(i) // Get details for a specific date based on the increment value
            const weatherDetails = // Extract specific weather details from data based on index
                getWeatherDetails(data, i)

            result.push({
                ...dateDetails,
                ...weatherDetails
            })
        }

        return result
    }

const // Get details for a specific date based on the increment value
    getDateDetails = increment => {
        const date = new Date()
        date.setDate(date.getDate() + increment)
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        const dateString = `${year}/${month}/${day}`
        const weekday = weekdays[date.getDay()]

        return { dateString, weekday }
    }

const // Extract specific weather details from data based on index
    getWeatherDetails = (data, index) => {
        const daily = data['result']['daily']
        const weather_code = daily['sky' + 'con'][index]['value']
        const weather = weathers[weather_code]['description']
        const icon = weathers[weather_code]['icon']
        const windSpeed = daily['wind'][index]['avg']
        const wind = getWindForceLevel(windSpeed)['level']

        return { weather, icon, wind }
    }

const // Get wind details based on the degree value
    getWindDetails = deg => {
        for (const wind of windDirections) {
            if ((deg >= wind.range[0] && deg <= 360) || (deg >= 0 && deg <= wind.range[1])) {
                return {
                    direction: wind.direction,
                    symbol: wind.symbol,
                    centerAngle: wind.centerAngle
                }
            }
        }
    }

const // Provide a description for the air quality based on the AQI value
    getAirQualityDescription = aqi => {
        const ranges = [0, 51, 101, 151, 201, 301]
        const descriptions = ['优', '良', '轻度污染', '中度污染', '重度污染', '严重污染']

        for (let i = 0; i < ranges.length; i++) {
            if (aqi < ranges[i]) {
                return descriptions[i - 1]
            }
        }

        return descriptions[descriptions.length - 1]
    }

const // Transform the raw weather data into a more usable format
    transformData = rawData => {
        const {
            server_time,
            result: { daily }
        } = rawData
        const update_time = server_time * 1000

        return {
            city: '江门', // <- 这个没有，暂时写死成江门
            update_time, // <- 精准到秒的时间戳来的，可以用new Date(xxx)转成自己想要的格式
            data: daily['astro'].map(
                (
                    astro,
                    index // Transform daily weather data based on astronomical and daily data for a specific index
                ) => transformDailyData(astro, daily, index)
            )
        }
    }

const // Transform daily weather data based on astronomical and daily data for a specific index
    transformDailyData = (astro, daily, index) => {
        const day = new Date(astro.date).toLocaleDateString('zh-CN', { month: 'long', day: 'numeric' })
        const date = astro.date.split('T')[0]
        const week = new Date(astro.date).toLocaleDateString('zh-CN', { weekday: 'long' })

        const {
            ['sky' + 'con_08h_20h']: weather_day,
            ['sky' + 'con_20h_32h']: weather_night,
            temperature: temperatureData,
            humidity: humidityData,
            wind: windData,
            air_quality: airData,
            precipitation: rainData
        } = daily

        const humidity = humidityData[index]['avg'] + '%'
        const win = getWindDetails(windData[index]['avg']['direction']).direction
        const win_speed = getWindForceLevel(windData[index]['avg']['speed']).level
        const win_meter = windData[index]['avg']['speed']
        const air = airData['aqi'][index]['avg']['chn']
        const air_level = getAirQualityDescription(air)
        const rain = rainData[index]['avg']
        const wea = weathers[weather_day[index].value].description
        const wea_day = weathers[weather_day[index].value].description
        const wea_night = weathers[weather_night[index].value].description
        const tem = temperatureData[index]['avg']
        const tem1 = temperatureData[index]['max']
        const tem2 = temperatureData[index]['min']

        return {
            day, // 9月15日
            date, // 2020-09-15
            week, // 星期三
            wea, // 阴 #实时天气情况
            wea_day, // 阵雨 #白天天气情况
            wea_night, // 阵雨 #夜间天气情况
            tem, // 25 #当前温度
            tem1, // 29 #一天最高温
            tem2, // 23 #一天最低温
            humidity, // 97% #湿度（没有可以不写）<- 有的
            win, // 东南风  #实时风向
            win_speed, // <3级 #风速等级
            win_meter, // 小于12km/h #风速
            air, // 14 #空气质量
            air_level, // 优 #空气质量等级
            rain // 雨量(mm)
        }
    }

const get7DaysWeather = async (latitude = 113.08220064926728, longitude = 22.708824208660197, days = 7) => {
    try {
        const response = await getDailyWeather(latitude, longitude, days)
        const rawData = JSON.parse(response.data)
        if (typeof rawData['result']['daily'] === 'object') {
            return transformData(rawData)
        } else {
            console.error(response)
        }
    } catch (error) {
        throw new Error('接口请求失败：' + error)
    }
    throw new Error('接口请求失败')
}

const getCurrentWeather = async (latitude = 113.08220064926728, longitude = 22.708824208660197, hours = 1) => {
    try {
        const response = await getHourlyWeather(latitude, longitude, hours)
        const rawData = JSON.parse(response.data)
        // console.log(rawData)
        if (rawData['result'] && typeof rawData['result']['hourly'] === 'object') {
            const hourly = rawData['result']['hourly']
            const weather_code = hourly['sky' + 'con'][0]['value']
            const weather = weathers[weather_code]['description']
            // const icon = weathers[weather_code]['icon']
            const windSpeed = hourly['wind'][0]['avg']
            const wind = getWindForceLevel(windSpeed)['level']
            const date = hourly['sky' + 'con'][0]['datetime'].substring(5, 10)
            return { wind, weather, date }
        } else {
            console.error(response)
        }
    } catch (error) {
        throw new Error('接口请求失败：' + error)
    }
    throw new Error('接口请求失败')
}
export {
    getDailyWeather,
    getHourlyWeather,
    getMinutelyWeather,
    get7DaysWeather,
    getCurrentWeather,
    get7DaysWeatherData
}
